<template>
    <div class="game-container">
      <button v-if="!isGameActive" @click="startGame">开始游戏</button>
      <div v-if="isGameActive" @click="checkClick" class="container">
        <div
          v-for="(circle, index) in circles"
          :key="index"
          class="circle"
          :style="{ left: circle.x + 'px', top: circle.y + 'px' }"
        ></div>
        <p>得分: {{ score }}</p>
        <p>剩余时间: {{ timeLeft }}秒</p>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  
  const circles = ref([]);
  const score = ref(0);
  const timeLeft = ref(30); // 游戏持续时间（秒）
  const isGameActive = ref(false);
  let timer = null;
  
  // 随机生成圆圈
  function createCircle() {
    const diameter = 50; // 圆圈直径
    const x = Math.random() * (window.innerWidth - diameter);
    const y = Math.random() * (window.innerHeight - diameter);
    circles.value.push({ x, y });
  }
  
  // 检查点击是否命中圆圈
  const checkClick = (event) => {
    const rect = event.target.getBoundingClientRect();
    const clickedX = event.clientX - rect.left;
    const clickedY = event.clientY - rect.top;
  
    circles.value.forEach((circle, index) => {
      // 检查点击是否在圆圈内
      if (
        clickedX >= circle.x &&
        clickedX <= circle.x + 50 &&
        clickedY >= circle.y &&
        clickedY <= circle.y + 50
      ) {
        score.value++; // 增加得分
        circles.value.splice(index, 1); // 移除被点击的圆圈
        createCircle(); // 生成新的圆圈
      }
    });
  };
  
  // 启动游戏
  const startGame = () => {
    isGameActive.value = true;
    score.value = 0;
    circles.value = [];
    timeLeft.value = 30; // 设置倒计时
    createCircle(); // 生成初始圆圈
  
    timer = setInterval(() => {
      if (timeLeft.value > 0) {
        timeLeft.value--;
      } else {
        endGame(); // 时间到，结束游戏
      }
    }, 1000);
  };
  
  // 结束游戏
  const endGame = () => {
    isGameActive.value = false;
    clearInterval(timer);
    alert(`游戏结束！你的得分是 ${score.value}`);
  };
  
  // 组件销毁时清理定时器
  onUnmounted(() => {
    clearInterval(timer);
  });
  </script>
  
  <style scoped>
  .game-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100vw;
    height: 100vh;
  }
  
  .container {
    position: relative;
    width: 100vw;
    height: 100vh;
    background-color: #d0d0d0; /* 背景颜色 */
    overflow: hidden; /* 防止圆圈超出边界 */
  }
  
  .circle {
    position: absolute;
    width: 50px; /* 圆圈的直径 */
    height: 50px; /* 圆圈的直径 */
    background-color: rgba(255, 0, 0, 0.5); /* 圆圈颜色 */
    border-radius: 50%; /* 使元素为圆形 */
    pointer-events: none; /* 使圆圈不阻塞鼠标事件 */
  }
  
  button {
    padding: 10px 20px;
    font-size: 18px;
    cursor: pointer;
  }
  </style>